/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package core.modules.communication.test;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServer;

import org.jboss.remoting.Client;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.callback.Callback;
import org.jboss.remoting.callback.HandleCallbackException;
import org.jboss.remoting.callback.InvokerCallbackHandler;
import org.jboss.remoting.transport.Connector;
import org.jboss.remoting.transport.bisocket.Bisocket;
import org.jboss.remoting.transport.bisocket.BisocketServerInvoker;
import org.jboss.remoting.transport.socket.SocketServerInvoker;

import core.modules.communication.test.BisocketSampleServer.SampleInvocationHandler;

/**
 * This class and org.jboss.remoting.samples.bisocket.BisocketSampleServer
 * demonstrate how to how to make an invocation and how to set up push callbacks
 * over the bisocket transport.
 * 
 * The reason for the existance of the bisocket transport, which is derived from
 * the socket transport, is to make it possible to do push callbacks to a client
 * which is unable to create a ServerSocket, either due to security restrictions
 * or due to the fact that it is behind a firewall.
 * 
 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
 * @version $Revision: 1.1 $
 *          <p>
 *          Copyright May 1, 2008
 *          </p>
 */
public class BisocketSampleClient {
	// public void makeInvocation(String locatorURI) throws Throwable
	// {
	// // Create client.
	// InvokerLocator clientLocator = new InvokerLocator(locatorURI);
	// Client client = new Client(clientLocator, "MYSYS");
	// client.connect();
	// System.out.println("client is connected");
	//
	// // Test connection.
	// if ("abc".equals(client.invoke("abc")))
	// System.out.println("connection is good");
	// else
	// System.out.println("Should have gotten \"abc\" in reply");
	//
	// // Set up push callbacks. Tell the Connector created by
	// Client.addListener()
	// // that it is a callback Connector, which tells the BisocketServerInvoker
	// // not to create a ServerSocket.
	// HashMap metadata = new HashMap();
	// metadata.put(Bisocket.IS_CALLBACK_SERVER, "true");
	// TestCallbackHandler callbackHandler = new TestCallbackHandler();
	// client.addListener(callbackHandler, metadata);
	//
	// // Use reflection to verify that the callback BisocketServerInvoker did
	// not
	// // create a ServerSocket.
	// Set callbackConnectors = client.getCallbackConnectors(callbackHandler);
	// if (callbackConnectors.size() != 1)
	// {
	// System.out.println("There should be one callback Connector");
	// }
	// else
	// {
	// Connector callbackConnector = (Connector)
	// callbackConnectors.iterator().next();
	// BisocketServerInvoker serverInvoker = (BisocketServerInvoker)
	// callbackConnector.getServerInvoker();
	// Field field =
	// SocketServerInvoker.class.getDeclaredField("serverSockets");
	// field.setAccessible(true);
	// List serverSockets = (List) field.get(serverInvoker);
	// System.out.println("number of ServerSockets held by callback BisocketServerInvoker: "
	// + serverSockets.size());
	// }
	//
	// // Request callback.
	// client.invoke("CALLBACK");
	// if (callbackHandler.getCounter() == 1)
	// System.out.println("received callback");
	// else
	// System.out.println("didn't receive callback");
	//
	// client.removeListener(callbackHandler);
	// client.disconnect();
	// }

	protected Connector connector;
	protected Client client;
	private InvokerLocator locator;
	protected static BisocketSampleClient bclient;
	static String serverLocatorURI = "socket://192.168.1.11:8884";
	static String clientLocatorURI = "socket://192.168.1.12:8888";

	protected void setupServer() throws Exception {
		// Create the InvokerLocator based on url string format
		// to indicate the transport, host, and port to use for the
		// server invoker.
		locator = new InvokerLocator(serverLocatorURI);

		connector = new Connector(locator);

		// Creates all the connector's needed resources, such as the server
		// invoker.
		connector.create();

		// Create the handler to receive the invocation request from the client
		// for processing.
		SampleInvocationHandler2 invocationHandler = new SampleInvocationHandler2();
		connector.addInvocationHandler("MYSYS", invocationHandler);

		// Start server.
		connector.start();
		System.out.println("Started remoting server with locator uri of: "
				+ serverLocatorURI);
	}

	protected void setupClient() throws Exception {
		client = new Client(new InvokerLocator(clientLocatorURI), "MYSYS");
		client.connect();
	}

	public static void main(String[] args) {
		try {
//			String host = InetAddress.getLocalHost().getHostName();
//			int port = BisocketSampleServer.port;
			bclient = new BisocketSampleClient();
			bclient.setupServer();
			bclient.setupClient();
			test();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	static class SampleInvocationHandler2 implements ServerInvocationHandler {
		public void addListener(InvokerCallbackHandler callbackHandler) {
		}

		public Object invoke(final InvocationRequest invocation)
				throws Throwable {
			//System.out.println("SampleInvocationHandler2.invoke()");
			Object param = invocation.getParameter();
			ArrayList<String> stringList = (ArrayList<String>) param;
			//System.out.println(serverLocatorURI +" invoke");
			wypisz(stringList);
			return null;
		}

		public void removeListener(InvokerCallbackHandler callbackHandler) {
		}

		public void setMBeanServer(MBeanServer server) {
		}

		public void setInvoker(ServerInvoker invoker) {
		}
	}

	public static void test() {
		String s = "s";
		long t= System.currentTimeMillis();
		long end = t+30000;
		int i=1;
		while(System.currentTimeMillis() < end) {
			try {
				Message message = new Message(serverLocatorURI, s+i++);
				//System.out.println("bclient == null: " + bclient == null);
				//System.out.println("bclient.client == null: " + bclient.client == null);
				bclient.client.invoke(message);
				
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void wypisz(ArrayList<String> stringList) {
		for(String s : stringList) {
			//System.out.print(s);
			//System.out.print(", ");
		}
		//System.out.println();
	}
}